import logging
import sys
from typing import Any, Dict

from app.core.config import settings
from app.core.context import get_request_id


class RequestIdFilter(logging.Filter):
    """为日志记录添加请求ID的过滤器"""

    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = get_request_id() or "no_request"
        return True


class UTF8Formatter(logging.Formatter):
    """处理UTF-8编码的日志格式化器"""

    def format(self, record: logging.LogRecord) -> str:
        if not isinstance(record.msg, str):
            record.msg = str(record.msg)
        return super().format(record)


class UTF8StreamHandler(logging.StreamHandler):
    """处理UTF-8编码的流处理器"""

    def __init__(self, stream=None):
        super().__init__(stream)
        self.stream = stream or sys.stdout
        if hasattr(self.stream, "reconfigure"):
            self.stream.reconfigure(encoding="utf-8")

    def emit(self, record: logging.LogRecord) -> None:
        try:
            msg = self.format(record)
            if not isinstance(msg, str):
                msg = str(msg)
            self.stream.write(msg + self.terminator)
            self.flush()
        except Exception:
            self.handleError(record)


def get_logging_config() -> Dict[str, Any]:
    """获取日志配置"""
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "()": "app.core.logging.UTF8Formatter",
                "format": "%(asctime)s [%(levelname)s] - [%(request_id)s] - %(name)s: %(message)s",
                "datefmt": "%Y-%m-%d %H:%M:%S",
            },
        },
        "filters": {
            "request_id": {
                "()": "app.core.logging.RequestIdFilter",
            },
        },
        "handlers": {
            "console": {
                "class": "app.core.logging.UTF8StreamHandler",
                "formatter": "default",
                "filters": ["request_id"],
                "stream": sys.stdout,
            },
            "file": {
                "class": "logging.handlers.RotatingFileHandler",
                "formatter": "default",
                "filters": ["request_id"],
                "filename": "app.log",
                "maxBytes": 10485760,  # 10MB
                "backupCount": 5,
                "encoding": "utf-8",
            },
        },
        "root": {
            "level": "DEBUG" if settings.DEBUG else "INFO",
            "handlers": ["console", "file"],
        },
    }


def setup_logging() -> None:
    """设置日志配置"""
    from logging.config import dictConfig

    config = get_logging_config()
    dictConfig(config)
    logger = logging.getLogger(__name__)
    logger.debug("Logging system initialized")
